package tio.study.showcase.server;

import lombok.extern.slf4j.Slf4j;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.server.intf.TioServerHandler;
import tio.study.showcase.common.ShowcaseAbsTioHandler;
import tio.study.showcase.common.ShowcasePacket;
import tio.study.showcase.common.Type;
import tio.study.showcase.common.intf.AbsShowcaseBsHandler;
import tio.study.showcase.server.handler.*;

import java.util.HashMap;
import java.util.Map;


/**
 * @author tanyaowu
 */
@Slf4j
public class ShowcaseServerTioHandler extends ShowcaseAbsTioHandler implements TioServerHandler {
	private static Map<Byte, AbsShowcaseBsHandler<?>> handlerMap = new HashMap<Byte, AbsShowcaseBsHandler<?>>();

	static {
		handlerMap.put(Type.GROUP_MSG_REQ, new GroupMsgReqHandler());
		handlerMap.put(Type.HEART_BEAT_REQ, new HeartbeatReqHandler());
		handlerMap.put(Type.JOIN_GROUP_REQ, new JoinGroupReqHandler());
		handlerMap.put(Type.LOGIN_REQ, new LoginReqHandler());
		handlerMap.put(Type.P2P_REQ, new P2PReqHandler());
	}

	/**
	 * 处理消息
	 */
	@Override
	public void handler(Packet packet, ChannelContext channelContext) throws Exception {
		ShowcasePacket showcasePacket = (ShowcasePacket) packet;
		Byte type = showcasePacket.getType();
		AbsShowcaseBsHandler<?> showcaseBsHandler = handlerMap.get(type);
		if (showcaseBsHandler == null) {
			log.error("{}, 找不到处理类，type:{}", channelContext, type);
			return;
		}
		showcaseBsHandler.handler(showcasePacket, channelContext);
		return;
	}
}
